//
//  MineViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/10.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "CompanyMineViewController.h"
#import "AppDelegate.h"
#import "MineCell.h"
#import "MineHeaderView.h"
#import "CompanyChatViewController.h"
#import "PMineBusinessCardViewController.h"
#import "PMineInviteFriendViewController.h"
#import "PMineWalletViewController.h"
#import "PMineAccountSettingViewController.h"
#import "CompanyMineGeneralizeViewController.h"

#import "CompanyRetestViewController.h"
#import "CompanyResumeManagementViewController.h"
#import "CompanyPrivacySettingViewController.h"
#import "CompanyMineCollectViewController.h"
#import "CompanyMineBaseInfoViewController.h"
#import "CompanyMineIntegrityEmployerViewController.h"
#import "IDSelectViewController.h"
#import "CompanyFirstInfoViewController.h"
#import "PersonalWorkExperienceViewController.h"
#import "CompanySecondInfoViewController.h"
#import "PersonalFirstInfoViewController.h"
#import "PersonalEducationInfoViewController.h"
#import "CompanyInfoViewController.h"
#import "GeneralWebViewViewController.h"
#import "CFindPublishedNewsFlashViewController.h"
#import "FeedbackViewController.h"

@interface CompanyMineViewController ()<UITableViewDelegate, UITableViewDataSource, MineHeaderViewDelegate>
{
    NSArray *itemDataArray;
    UITableView *mineTableView;
}
@property (nonatomic, strong) MineHeaderView *tableViewHeaderView;
@property (nonatomic, strong) NSMutableArray *chatListArr;
@end

@implementation CompanyMineViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    if (_tableViewHeaderView) {
        [self chatCount];
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)chatCount {
    TIMManager *manager = [TIMManager sharedInstance];
    self.chatListArr = [NSMutableArray arrayWithCapacity:0];
    NSArray *convs = [manager getConversationList];
    [self.chatListArr addObjectsFromArray:convs];
    __weak __typeof(self)weakSelf = self;
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (TIMConversation *conv in convs) {
        if ([conv getType] == TIM_SYSTEM) {
            continue;
        }
        [arr addObject:[NSString stringWithFormat:@"%@", [conv getReceiver]]];
    }
    
    [[TIMFriendshipManager sharedInstance] getUsersProfile:arr forceUpdate:YES succ:^(NSArray<TIMUserProfile *> *profiles) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSMutableArray *reloadArr = [NSMutableArray arrayWithCapacity:0];
        for (TIMUserProfile *profile in profiles) {
            NSLog(@"user=%@", profile);
            NSMutableArray *listArr = [NSMutableArray arrayWithCapacity:0];
            if (profile.role == 2) {
                for (TIMConversation *tempConv in strongSelf.chatListArr) {
                    if ([[tempConv getReceiver] isEqualToString:profile.identifier]) {
                        [listArr addObject:tempConv];
                    }
                }
            }
            if (listArr&&listArr.count) {
                for (TIMConversation *conv in listArr) {
                    if ([conv getType] == TIM_SYSTEM) {
                        continue;
                    }
                    [reloadArr addObject:@""];
                }
            }
        }
        if (reloadArr&&reloadArr.count) {
            strongSelf.tableViewHeaderView.resumeCount = [NSString stringWithFormat:@"%lu", (unsigned long)reloadArr.count];
        } else {
            strongSelf.tableViewHeaderView.resumeCount = @"0";
        }
    } fail:^(int code, NSString *msg) {
        NSLog(@"%@", msg);
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadDataBaseData) name:NotificationForCompanyMineBaseDataRefresh object:nil];
    
    NSString *mine_info_text = @"审核中";
    if (([DataToolsControl sharedManager].companyBaseInfoModel && [DataToolsControl sharedManager].companyBaseInfoModel.audit.length)) {
        if ([[DataToolsControl sharedManager].companyBaseInfoModel.audit integerValue]==1) {
            mine_info_text = @"已认证";
        } else if ([[DataToolsControl sharedManager].companyBaseInfoModel.audit integerValue]==2) {
            mine_info_text = @"审核中";
        } else {
            mine_info_text = @"认证失败";
        }
    } else {
        mine_info_text = @"未认证";
    }
    NSString *mine_credit_text = @"拥有专属保障标示";
    if (([DataToolsControl sharedManager].companyBaseInfoModel && [DataToolsControl sharedManager].companyBaseInfoModel.integrity_union.length)) {
        if ([[DataToolsControl sharedManager].companyBaseInfoModel.integrity_union integerValue]==1) {
            mine_credit_text = @"已开启";
        }
    }
    
    itemDataArray = @[@[@[@"p_mine_businesscard", @"我的名片", @""], @[@"c_mine_info", @"企业信息", mine_info_text], @[@"p_mine_status", @"职位推广", @"职位曝光率迅速提升80%"], @[@"p_mine_newsflash", @"已发快讯", @""], @[@"p_mine_credit", @"诚信雇主", mine_credit_text], @[@"p_mine_invate", @"邀请好友", @"每邀请一位可赚30-110聘豆"]], @[@[@"p_mine_wallet", @"我的钱包", @""], @[@"p_mine_privacy", @"隐私设置", @""], @[@"p_mine_setting", @"账号设置", @""], @[@"p_mine_feedback", @"意见反馈", @""]]];
    
    [self initUI];
}
- (void)initUI {
    mineTableView = [UIToolsControl initTableViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-HeightOfTabBar) target:self style:UITableViewStyleGrouped];
    mineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mineTableView.rowHeight = MineCellHeight;
    mineTableView.separatorInset = UIEdgeInsetsZero;
    mineTableView.backgroundColor = THEMECOLOR_OF_GRAY;
    [self.view addSubview:mineTableView];
    if (@available(iOS 11.0, *)) {
        mineTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (itemDataArray.count) {
        return itemDataArray.count;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (itemDataArray && itemDataArray.count) {
        return [itemDataArray[section] count];
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineCell *cell = [tableView dequeueReusableCellWithIdentifier:isCellID];
    if (!cell) {
        cell = [[MineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:isCellID];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    [cell reloadDataIcon:itemDataArray[indexPath.section][indexPath.row][0] leftText:itemDataArray[indexPath.section][indexPath.row][1] rightText:itemDataArray[indexPath.section][indexPath.row][2] indexPath:indexPath];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section) {
        switch (indexPath.row) {
            case 0: { // 钱包
                PMineWalletViewController *PMWVC = [[PMineWalletViewController alloc] init];
                PMWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMWVC animated:YES];
            } break;
            case 1: { // 隐私
                CompanyPrivacySettingViewController *PMPSVC = [[CompanyPrivacySettingViewController alloc] init];
                PMPSVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMPSVC animated:YES];
            } break;
            case 2: { // 账号
                PMineAccountSettingViewController *PMASVC = [[PMineAccountSettingViewController alloc] init];
                PMASVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMASVC animated:YES];
            } break;
            case 3: { // 意见反馈
                FeedbackViewController *FVC = [[FeedbackViewController alloc] init];
                FVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:FVC animated:YES];
            } break;
            default:
                break;
        }
    } else {
        switch (indexPath.row) {
            case 0: { // 我的名片
                PMineBusinessCardViewController *PMBCVC = [[PMineBusinessCardViewController alloc] init];
                PMBCVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PMBCVC animated:YES];
            } break;
            case 1: { // 企业信息
                CompanyInfoViewController *CIVC = [[CompanyInfoViewController alloc] init];
                CIVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:CIVC animated:YES];
            } break;
            case 2: { // 职位推广
                GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
                GWVC.showType = GeneralWebViewTypeOfGeneralize;
                GWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:GWVC animated:YES];
            } break;
            case 3: { // 已发快讯
                CFindPublishedNewsFlashViewController *PNFVC = [[CFindPublishedNewsFlashViewController alloc] init];
                PNFVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:PNFVC animated:YES];
            } break;
            case 4: { // 诚信雇主
                GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
                GWVC.showType = GeneralWebViewTypeOfIntegrityEmployer;
                GWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:GWVC animated:YES];
            } break;
            case 5: { // 邀请好友 （H5）
                GeneralWebViewViewController *GWVC = [[GeneralWebViewViewController alloc] init];
                GWVC.showType = GeneralWebViewTypeOfInviteFriend;
                GWVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:GWVC animated:YES];
            } break;
            default:
                break;
        }
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section) {
        return [UIToolsControl initViewWithFrame:CGRectMake(0, 0, WIDTH, 10*Scale) backgroundColor:THEMECOLOR_OF_GRAY];
    } else {
        return self.tableViewHeaderView;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section) {
        return 10*Scale;
    }
    return 235*Scale+((isiPhoneX||isiPhoneXr||isiPhoneXsMax)?ScalePS(20):0);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}

- (void)mineHeaderViewTap:(MineHeaderViewTapType)type {
    switch (type) {
        case MineHeaderViewTapTypeOfRoleSwitch: {
            NSLog(@"切换角色");
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
            dic = [UIToolsControl getPublicParameter];
            [dic setObject:@"2" forKey:@"user_role"];
            [BaseNetManager requestWithMethod:POST path:Change_Role_URL params:dic successBlock:^(NSDictionary *responseObject) {
                if ([responseObject[@"code"] integerValue] == 2000) {
                    UD_SetOForK(@"2", isUserRole);
                    
                    NSDictionary *data = responseObject[@"data"];
                    if (data[@"user_guide"] && [data[@"user_guide"] length] && ([data[@"user_guide"] isEqualToString:@"choose_role"])) { // 用户还没选角色 （选择用户角色）
                        IDSelectViewController *IDSVC = [[IDSelectViewController alloc] init];
                        IDSVC.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:IDSVC animated:NO];
                    } else {
                        if ([data[@"user_guide"] isEqualToString:@"company_add_job"]) { // 添加工作 
                            [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
                                [SharedApp showViewController:TabBarTypeOfCompany];
                                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                tabBarController.selectedIndex = 1;
                            }];
                        } else if ([data[@"user_guide"] isEqualToString:@"company_create"]) { // 招聘者下面没有企业的话就会引导创建
                            CompanyFirstInfoViewController *IDSVC = [[CompanyFirstInfoViewController alloc] init];
                            IDSVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:IDSVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"company_info"]) { // 填写企业信息
                            CompanySecondInfoViewController *IDSVC = [[CompanySecondInfoViewController alloc] init];
                            IDSVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:IDSVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"company_audit"]) { // 企业未认证
                            CompanyInfoViewController *CIVC = [[CompanyInfoViewController alloc] init];
                            CIVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:CIVC animated:NO];
                        } else if (([data[@"user_guide"] isEqualToString:@"resume_create"])) { // 创建简历页
                            PersonalFirstInfoViewController *PMRVC = [[PersonalFirstInfoViewController alloc] init];
                            PMRVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:PMRVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"resume_edu"]) { // 完善简历中教育经历
                            if (data[@"is_graduate"] && ([data[@"is_graduate"] integerValue] == 0)) {
                                [DataToolsControl sharedManager].idType = IDTypeOfWorker;
                            } else {
                                [DataToolsControl sharedManager].idType = IDTypeOfFreshGraduate;
                            }
                            
                            PersonalEducationInfoViewController *PMRVC = [[PersonalEducationInfoViewController alloc] init];
                            PMRVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:PMRVC animated:NO];
                        } else if ([data[@"user_guide"] isEqualToString:@"resume_work"]) { // 完善简历中工作经历
                            PersonalWorkExperienceViewController *PMRVC = [[PersonalWorkExperienceViewController alloc] init];
                            PMRVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:PMRVC animated:NO];
                        } else {
                            SVPHUDShow;
                            [DataToolsControl getMyBaseInfoForWorker:^(BOOL requestFlag) {
                                SVPHUDDismiss;
                                [SharedApp showViewController:TabBarTypeOfPersonal];
                                UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                tabBarController.selectedIndex = tabBarController.viewControllers.count-1;
                            }];
                        }
                    }
                } else {
                    SVPHUDError(responseObject[@"msg"]);
                }
            } failurBlock:^(NSError *error) {
                SVPHUDError(NetErrorAlertText);
            }];
        } break;
        case MineHeaderViewTapTypeOfEditInfo: {
            NSLog(@"编辑信息");
            CompanyMineBaseInfoViewController *CMBIVC = [[CompanyMineBaseInfoViewController alloc] init];
            CMBIVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:CMBIVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfResume: {
            NSLog(@"初试沟通");
            CompanyChatViewController *PMRVC = [[CompanyChatViewController alloc] init];
            PMRVC.hiddenTabBarFlag = YES;
            PMRVC.navigationItem.title = @"初试沟通";
            PMRVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfDeliver: {
            NSLog(@"复试邀请");
            CompanyRetestViewController *CRVC = [[CompanyRetestViewController alloc] init];
            CRVC.hidesBottomBarWhenPushed = YES;
            CRVC.isPerson = NO;
            [self.navigationController pushViewController:CRVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfInvate: {
            NSLog(@"简历管理");
            CompanyResumeManagementViewController *PMRIVC = [[CompanyResumeManagementViewController alloc] init];
            PMRIVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMRIVC animated:YES];
        } break;
        case MineHeaderViewTapTypeOfAttention: {
            NSLog(@"人才收藏");
            CompanyMineCollectViewController *PMCVC = [[CompanyMineCollectViewController alloc] init];
            PMCVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:PMCVC animated:YES];
        } break;
        default:
            break;
    }
}
- (MineHeaderView *)tableViewHeaderView {
    if (!_tableViewHeaderView) {
        _tableViewHeaderView = [[MineHeaderView alloc] initWithTarget:self roleType:IDTypeOfCompany];
        _tableViewHeaderView.userInteractionEnabled = YES;
        _tableViewHeaderView.backgroundColor = COLOR_OF_WHITE;
        [self chatCount];
    }
    return _tableViewHeaderView;
}
- (void)loadDataBaseData {
    __weak __typeof(self)weakSelf = self;
    [DataToolsControl getMyBaseInfoForCompany:^(BOOL requestFlag) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (requestFlag) {
            [strongSelf.tableViewHeaderView setCompanyPartBaseInfo];
        }
    }];
}

@end
